//  apiv1 总api接口

const base = require('./controller');
const dataBuilder = require('../common/DataBuilder');
module.exports = class extends base {


    constructor(ctx) {
        super(ctx);
        //初始化模型
        this.painpointModel = this.model('pain_points');
        this.painpointsolutionModel = this.model('pain_points_solutions');
        this.painpointDataBuilder = new dataBuilder.pain_points();


        //初始化数据
        this.id = this.get('id');
        this.pd = ctx.state.pd ? ctx.state.pd : {};



        //状态定义
        this.dbStatus = {
            normal: {'status': 'normal'},
            delete: {'status': 'deleted'},
            able: {'status': 'able'},
            undisposed: {'status': 'undisposed'},
            disposed: {'status': 'disposed'},
            backed: {'status': 'backed'},
            notdeleted: {'status': ['!=', 'deleted']},
            open: {'status': 'open'},//open', 'unopen
            unopen: {'status': 'unopen'},//open', 'unopen
        };

        this.dbField = {
            ipField: 'create_ip,update_ip,delete_ip',
            timeField: "create_time,delete_time,update_time"
        };
        this.dbPk = {
            pain_points_solutions: "pk_pain_point_solution",
            pain_points: "pk_pain_point",
        }
    }

    //1.1添加挑战
    async createpainpointAction() {

        let postdata = this.pd;
        //todo 没做权限
        //初始化数据
        postdata['pk_pain_point'] = think.uuid('v4');
        postdata['opeater_id'] = '0';
        postdata['is_carousel'] = 'false';
        postdata['is_open_solution'] = 'unopen';
        postdata['status'] = 'able';
        postdata['create_time'] = think.nowTimestamp();
        postdata['update_time'] = 0;
        postdata['delete_time'] = 0;
        postdata['create_ip'] = this.ip;
        postdata['update_ip'] = '0';
        postdata['delete_ip'] = '0';
        //构建数据
        let dbdata = this.painpointDataBuilder.build(postdata);
        if (dbdata.errno === 0) {
            if ((await this.painpointModel.add(dbdata.data)) >= 0) {
                return this.resSuccessWithData(postdata['pk_pain_point']);
            }
            return this.resErrmsg('系统繁忙,请稍后再试')
        } else {
            return this.resErrmsg(dbdata.errmsg);
        }
    }

    //3.4痛点基本信息教师
    async painpointdescAction() {
        if (think.isEmpty(this.id)) return this.resErrmsg('id不能为空');
        return this.resSelect(await this.painpointModel.fieldReverse('create_ip,update_ip,delete_ip,is_carousel,status').where(this.dbStatus.able).find(this.id))
    }


    // 轮播
    async carouselAction() {
        return this.resSelect(await this.painpointModel.field('pk_pain_point,cover').where({is_carousel: 'true'}).where(this.dbStatus.able).limit(5).select())
    }


    /**
     2.1当前痛点api|附带总信息条数
     post  /painpoint
     参数：pages:1,limit:3,oredername:'end_time'\'create_time'\'update_time',orderrule:desc|asc, period:past|now|forever|none,range_type:class|public
     默认：1,10,end_time,desc,now,
     返回：当前痛点集合，痛点总条数
     说明:
     period参数:
     past| 历史(即结束时间小于当前时间)
     now| 进行中
     forever| 没有截止时间(即时间为-1,)
     none 查询所有
     */
    async painpointAction() {
        let pd = this.pd;
        //初始化
        pd['pages'] = pd['pages'] ? pd['pages'] : 1;
        pd['limit'] = pd['limit'] ? pd['limit'] : 10;
        pd['oredername'] = pd['oredername'] ? pd['oredername'] : 'end_time';
        pd['orderrule'] = pd['orderrule'] ? pd['orderrule'] : 'desc';
        pd['period'] = pd['period'] ? pd['period'] : 'now';
        pd['range_type'] = pd['range_type'] ? pd['range_type'] : 'class';

        let dbdata = (new dataBuilder.pain_points_select_opion).build(pd);

        if (dbdata.errno === 0) {
            let where = {};
            switch (pd['period']) {
                case 'now': {
                    where = {
                        'end_time': ['>', think.nowTimestamp()]
                    }
                }
                    break;
                case "past": {
                    where = {
                        'end_time': ['<', think.nowTimestamp()]
                    }
                }
                    break;
                case 'forever': {
                    where = {
                        'end_time': ['=', -1]
                    }
                }
                    break;
                case 'none': {
                    return this.resSelect(await this.painpointModel.where(this.dbStatus.able).order(`${pd['oredername']} ${pd['orderrule']}`).page(pd['pages'], pd['limit']).fieldReverse(this.dbField.ipField).select());
                }
                    break;
            }
            let data = await this.painpointModel.where(where).where({"range_type": pd.range_type}).where(this.dbStatus.able).order(`${pd['oredername']} ${pd['orderrule']}`).page(pd['pages'], pd['limit']).fieldReverse(this.dbField.ipField).select();

            let itemcount = await this.painpointModel.where({"range_type": pd.range_type}).where(where).where(this.dbStatus.able).order(`${pd['oredername']} ${pd['orderrule']}`).page(pd['pages'], pd['limit']).count();
            data.push({"itemscount": itemcount});
            if (itemcount === 0) {
                return this.resEmpty();
            }
            {
                return this.resSelect(data);
            }


        } else {
            return this.resErrmsg(dbdata.errmsg);
        }
    }


    /**
     * 3.1公布   痛点解决方案
     post /painpointopensolution/:id
     */
    async painpointopensolutionAction() {
        if (think.isEmpty(this.id)) {
            return this.resErrmsg('痛点id不能为空');
        }
        return this.resUpdate(await this.painpointModel.where({pk_pain_point: this.id}).update({is_open_solution: 'open'}));
    }

    /**
     * 3.1_2取消公布  痛点解决方案
     post /painpointopensolution/:id
     */
    async painpointunopensolutionAction() {
        if (think.isEmpty(this.id)) {
            return this.resErrmsg('痛点id不能为空');
        }
        return this.resUpdate(await this.painpointModel.where({pk_pain_point: this.id}).update({is_open_solution: 'unopen'}));
    }

    /**
     * 3.2修改挑战
     post /modifypainpoint
     */
    async modifypainpointAction() {
        let postdata = this.pd;
        //todo 没做权限
        postdata['update_time'] = think.nowTimestamp();
        postdata['update_ip'] = this.ip;
        let dbdata = (new dataBuilder.pain_points_modify()).build(postdata);
        let saveData = dbdata.data;
        let pk = saveData['pk_pain_point'];
        delete saveData['pk_pain_point'];
        if (dbdata.errno === 0) {
            return this.resInsert(await this.painpointModel.where({'pk_pain_point': pk}).update(saveData));
        } else {
            return this.resErrmsg(dbdata.errmsg);
        }
    }

    /**
     *  痛点的提交方案数
     *  /painpointsolutionscount/:painpointid
     *  */

    async painpointsolutionscountAction() {
        if (think.isEmpty(this.id)) {
            return this.resErrmsg('痛点id不能为空');
        }
        return this.resSuccessWithData(await this.painpointsolutionModel.where({
            fk_pain_point: this.id,
            status: 'able'
        }).count())
    }


    /**
     * 痛点的提交方案数 批量
     * @returns {Promise.<*>}
     */
    async painpointsolutionscountmanyAction() {
        let query = this.pd.query;
        if (think.isEmpty(query)) {
            return this.resErrmsg('查询序列不能为空')
        }

        if (!think.isString(query)) return this.resErrmsg("参数必须是用逗号分隔的字符串");


        let queryArr = query.split(',');
        if (!think.isArray(queryArr)) return this.resErrmsg("参数可能有中文的逗号，请检查");

        let reg = /，/;

        if (query.match(reg)) {
            return this.resErrmsg("参数不能含有中文逗号");
        }

        let dbdata = await  this.painpointsolutionModel.field("fk_pain_point,count(*) as count").where({'fk_pain_point': ['in', query]}).group('fk_pain_point').where({status: "able"}).select();
        //结果

        //处理空数据
        let responseData = [];
        queryArr.forEach((key) => {

            let i = 0;
            for (; i < dbdata.length; i++) {
                let dbobj = dbdata[i];
                if (dbobj.fk_pain_point === key) {
                    responseData.push({[key]: dbobj.count});
                    return;
                } else {
                    continue;
                }
            }
            if (i >= dbdata.length) {
                responseData.push({[key]: 0});
                return;
            }
        });

        return this.resSelect(responseData);
    }

    /**
     *
     * 3.3删除挑战
     delete /delpainpoint/:painpointid*/
    async delpainpointAction() {
        if (think.isEmpty(this.id)) {
            return this.resErrmsg('痛点id不能为空');
        }
        return this.resDelete(await this.painpointModel.where({pk_pain_point: this.id}).update({status: 'deleted'}))
    }

    /**
     * 3.5已提交方案(附带总信息条数)
     参数：pages:1,limit:10,oredername:'score','create_time','praise','noscore',orderrule:desc|asc,type:manager|student
     默认：1,10,end_time,desc,public,now
     参数说明:
     oredername参数
     score 评分排序,
     create_time:创建时间排序,
     prise:热度排序,
     noscore:没有评分(获取未评分的数据)


     type参数
     manager 管理员端
     student 学生端


     */

    async painpointsolutionsAction() {
        if (think.isEmpty(this.id)) {
            return this.resErrmsg('痛点id不能为空');
        }
        let pd = this.pd;
        //初始化
        pd['pages'] = pd['pages'] ? pd['pages'] : 1;
        pd['limit'] = pd['limit'] ? pd['limit'] : 10;
        pd['ordername'] = pd['ordername'] ? pd['ordername'] : 'create_time';
        pd['orderrule'] = pd['orderrule'] ? pd['orderrule'] : 'desc';
        let dbdata = (new dataBuilder.solutions_option()).build(pd);
        if (dbdata.errno === 0) {
            switch (pd.type) {
                case "manager": {
                    return this.resSelect(await this.getpainpointsolutions(this.id, pd))
                }
                    break;
                case "student": {
                    let stat = await this.painpointModel.where({pk_pain_point: this.id}).getField('is_open_solution', true);
                    if (stat === 'open') {
                        return this.resSelect(await this.getpainpointsolutions(this.id, pd))
                    } else {
                        return this.resErrmsg('暂未公开该解决方案');
                    }
                }
                    break;
                default: {
                    return this.resErrmsg('type值为空')
                }
            }
        } else {
            return this.resErrmsg(dbdata.errmsg);
        }


    }

    //构建查询语句
    async getpainpointsolutions(painpointid, pd) {
        //解决特殊情况
        if (pd.ordername === 'noscore') {
            return await this.painpointsolutionModel.where(this.dbStatus.able).where({score: ['<=', 0]}).page(pd['pages'], pd['limit']).fieldReverse(this.dbField.ipField).where({fk_pain_point: this.id}).select();
        } else {
            return await this.painpointsolutionModel.where(this.dbStatus.able).order(`${pd.ordername} ${pd['orderrule']}`).page(pd['pages'], pd['limit']).fieldReverse(this.dbField.ipField).where({fk_pain_point: this.id}).select();
        }


    }


    /**
     * 方案详情
     get /solvtiondesc/:id
     */

    async solvtiondescAction() {
        if (think.isEmpty(this.id)) {
            return this.resErrmsg('方案id不能为空');
        }
        return this.resSelect(await this.painpointsolutionModel.where(this.dbStatus.notdeleted).fieldReverse(this.dbField.ipField).find(this.id));
    }

    /**
     * 打分
     * solutionscore
     */

    async solutionscoreAction() {
        if (think.isEmpty(this.id)) {
            return this.resErrmsg('方案id不能为空');
        }
        let score = this.pd.score;
        if (think.isEmpty(score)) return this.resErrmsg("分数不能为空");
        if (score <= 0 || score > 10) return this.resErrmsg('分数不合格');
        return this.resUpdate(await this.painpointsolutionModel.where({'pk_pain_point_solution': this.id}).update({score: score}));
    }


    //5.3 退回方案
    async backsolutionAction() {
        let postdata = this.pd;

        let solution_id = this.pd.fk_pain_point_solution ? this.pd.fk_pain_point_solution : 0;
        let flag = await this.painpointsolutionModel.where({pk_pain_point_solution: solution_id}).find();
        if (think.isEmpty(flag)) {
            return this.resErrmsg('该方案不存在');
        }

        //todo 没做权限

        postdata['status'] = 'backed';
        postdata['update_time'] = think.nowTimestamp();
        postdata['update_ip'] = this.ip;
        let dbdata = (new dataBuilder.solutions_back_reason()).build(postdata);
        if (dbdata.errno === 0) {

            delete postdata['fk_pain_point_solution'];
            delete postdata['fk_user'];
            return this.resUpdate(await  this.painpointsolutionModel.where({[this.dbPk.pain_points_solutions]: solution_id}).update(dbdata.data));
        } else {
            return this.resErrmsg(dbdata.errmsg);
        }
    }


    /**
     * 6.2 我的挑战
     get /userpainpoint/:userid
     */

    async userpainpointAction() {
        if (think.isEmpty(this.id)) {
            return this.resErrmsg('学习班级id不能为空');
        }
        return this.resSelect(await this.painpointModel.where({
            status: 'able',
            range_value: ['like', `%${this.id}%`]
        }).select())
    }

    //用户方案(的所有方案)
    async usersolutionAction() {
        if (think.isEmpty(this.id)) {
            return this.resErrmsg('用户id不能为空');
        }
        return this.resSelect(await this.painpointsolutionModel.fieldReverse(this.dbField.ipField).where({fk_user: this.id}).select())
    }

    /**
     * 9.1 提交方案
     post /addsolution
     */
    async addsolutionAction() {
        if (think.isEmpty(this.id)) {
            return this.resErrmsg('痛点id不能为空');
        }
        let flag = await  this.painpointModel.find(this.id);
        if (think.isEmpty(flag)) {
            return this.resErrmsg('该痛点不存在');
        }
        let postdata = this.pd;
        //todo 没做权限
        postdata['pk_pain_point_solution'] = think.uuid('v4');
        postdata['fk_pain_point'] = this.id;
        postdata['opeater_id'] = '0';
        postdata['score'] = 0;
        postdata['praise'] = 0;
        postdata['status'] = 'able';
        postdata['create_time'] = think.nowTimestamp();
        postdata['update_time'] = 0;
        postdata['delete_time'] = 0;
        postdata['create_ip'] = this.ip;
        postdata['update_ip'] = '0';
        postdata['delete_ip'] = '0';

        let dbdata = (new dataBuilder.solutions()).build(postdata);
        if (dbdata.errno === 0) {
            let flag = await this.painpointsolutionModel.add(dbdata.data);
            if (!think.isEmpty(flag)) {
                return this.resErrmsg('添加失败');
            } else {
                return this.resSelect(postdata['pk_pain_point_solution']);
            }

        } else {
            return this.resErrmsg(dbdata.errmsg);
        }
    }


    //修改方案
    async modifysolutionAction() {
        let postdata = this.pd;
        //todo 没做权限
        postdata['opeater_id'] = '0';
        postdata['update_time'] = think.nowTimestamp();
        postdata['update_ip'] = this.ip;
        let dbdata = (new dataBuilder.solutions_modify()).build(postdata);
        if (dbdata.errno === 0) {
            return this.resUpdate(await this.painpointsolutionModel.where({pk_pain_point_solution: dbdata.data.pk_pain_point_solution}).update(dbdata.data));
        } else {
            return this.resErrmsg(dbdata.errmsg);
        }
    }
};